/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    vector<int> ret;
public:
    vector<int> rightSideView(TreeNode* root) {
        if(root != nullptr)
            bfs(root);
        return ret;
    }
    void bfs(TreeNode* root) // 层序遍历保存每一层的最后一个节点
    {
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            int sz = q.size();
            for(int i = 0; i < sz; ++i)
            {
                auto e = q.front();
                q.pop();
                if(e->left)
                    q.push(e->left);
                if(e->right)
                    q.push(e->right);
                if(i == sz - 1)
                    ret.push_back(e->val);
            }
        }
    }
};